package com.whately.core.httpsession;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory;

import java.time.Duration;

/**
 * boot升级到2.2
 */
@Configuration
public class WhatelyHttpSessionRedisConfiguration {

   @Bean("connectionFactoryForSpringSession")
   @SpringSessionRedisConnectionFactory
   public RedisConnectionFactory connectionFactory4Session(GenericObjectPoolConfig genericObjectPoolConfig,RedisProperties properties){
       //通过配置RedisClusterConfiguration实例来创建工厂
       //构造该对象是传入Lettuce客户端配置和redis集群配置
       int dbIndex = 1;

       //redis客户端配置
       LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(createRedisConfiguration(dbIndex,properties),createLettuceClientConfiguration(genericObjectPoolConfig,properties));
       lettuceConnectionFactory.setDatabase(dbIndex);

       //不能加下面这句话，否则createClient会内存溢出
       //lettuceConnectionFactory.afterPropertiesSet();

       return lettuceConnectionFactory;
   }

    private LettuceClientConfiguration createLettuceClientConfiguration(GenericObjectPoolConfig genericObjectPoolConfig,RedisProperties properties){
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                builder =  LettucePoolingClientConfiguration.builder().
                commandTimeout(properties.getTimeout());

        builder.shutdownTimeout(Duration.ofMillis(3000L));
        builder.poolConfig(genericObjectPoolConfig);

        LettuceClientConfiguration lettuceClientConfiguration = builder.build();
        return lettuceClientConfiguration;
    }

    private RedisStandaloneConfiguration createRedisConfiguration(int dbIndex,RedisProperties properties){
        RedisStandaloneConfiguration redisConfiguration = new
                RedisStandaloneConfiguration(properties.getHost(),properties.getPort());
        redisConfiguration.setDatabase(dbIndex);
        redisConfiguration.setPassword(properties.getPassword());
        return redisConfiguration;
    }

}
